package com.cheer.ba.view.activity;

import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.H5Address;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.OilCardInfoModel;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.SystemUtils;
import com.cheer.ba.utils.TextViewUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.dialog.DialogUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 添加加油卡界面
 *
 * @author HQ
 *         created at 2017/5/10 0010 16:58
 */
public class AddOilCardAty extends BaseCommAty {

    //输入油卡卡号
    @BindView(R.id.id_input_oil_card_num_edit)
    EditText mEditCardNum;
    private String mCardNum;

    //服务协议
    @BindView(R.id.id_oil_service_agreement_txt)
    TextView mTxtService;

    @BindView(R.id.id_add_remind_img)
    ImageView mImgRemind;

    private static final char kongge = ' ';

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_add_oil_card, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.add_oil_card));
        int height = (int) (2565 * SystemUtils.getScreenWidth(aty) / 720);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
        mImgRemind.setLayoutParams(params);

        mEditCardNum.addTextChangedListener(new TextWatcher() {
            // 改变之前text长度
            int beforeTextLength = 0;
            // 改变之前的文字
            private CharSequence beforeChar;
            // 改变之后text长度
            int onTextLength = 0;
            // 是否改变空格或光标
            boolean isChanged = false;
            // 记录光标的位置
            int location = 0;
            private char[] tempChar;
            private StringBuffer buffer = new StringBuffer();
            // 已有空格数量
            int konggeNumberB = 0;

            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
                onTextLength = s.length();
                buffer.append(s.toString());
                if (onTextLength == beforeTextLength || onTextLength <= 3
                        || isChanged) {
                    isChanged = false;
                    return;
                }
                isChanged = true;
            }

            @Override
            public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                                          int arg3) {
                beforeTextLength = s.length();
                if (buffer.length() > 0) {
                    buffer.delete(0, buffer.length());
                }
                konggeNumberB = 0;
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == ' ') {
                        konggeNumberB++;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isChanged) {
                    location = mEditCardNum.getSelectionEnd();
                    int index = 0;
                    while (index < buffer.length()) {
                        if (buffer.charAt(index) == kongge) {
                            buffer.deleteCharAt(index);
                        } else {
                            index++;
                        }
                    }
                    index = 0;
                    int konggeNumberC = 0;
                    while (index < buffer.length()) {
                        if ((index - 4) % 5 == 0) {
                            buffer.insert(index, kongge);
                            konggeNumberC++;
                        }
                        index++;
                    }

                    if (konggeNumberC > konggeNumberB) {
                        location += (konggeNumberC - konggeNumberB);
                    }

                    tempChar = new char[buffer.length()];
                    buffer.getChars(0, buffer.length(), tempChar, 0);
                    String str = buffer.toString();
                    if (location > str.length()) {
                        location = str.length();
                    } else if (location < 0) {
                        location = 0;
                    }
                    mEditCardNum.setText(str);
                    Editable etable = mEditCardNum.getText();
                    Selection.setSelection(etable, location);
                    isChanged = false;
                }
            }
        });
        mCardNum = getIntent().getStringExtra(IntentKey.General.KEY_DATA);
        if (!StringUtils.isEmpty(mCardNum)) {
            mEditCardNum.setText(mCardNum);
        }
    }

    @Override
    public void initData() {
        setTitleRight("申请油卡", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showActivity(aty, HandleOilCardAty.class);
            }
        });
        TextViewUtils.setSpannableStyleColor(getString(R.string.add_oil_card_desc), 13, 20, mTxtService, R.color.color_main);

        mEditCardNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mCardNum = s + "";
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @OnClick({R.id.id_add_oil_card_num_btn, R.id.id_ask_oil_card_btn, R.id.id_oil_service_agreement_txt})
    public void onClick(View mView) {
        switch (mView.getId()) {
            //添加油卡卡号
            case R.id.id_add_oil_card_num_btn:
                if (StringUtils.isEmpty(mCardNum)) {
                    SVProgressHUD.showInfoWithStatus(aty, "请输入加油啦车队卡卡号");
                } else {
                    ((OilMealPresenter) presenter).bindOilCard(mCardNum.replaceAll(" ", "").trim());
                }
                break;
            //申请油卡卡号
            case R.id.id_ask_oil_card_btn:
                showActivity(aty, AskOilCardAty.class);
                break;
            //同意协议
            case R.id.id_oil_service_agreement_txt:
                CommH5Aty.startCommonH5(aty, H5Address.USER_RECHARGE, false);
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(ConstantTag.BIND_OIL_CARD, tag)) {
                OilCardInfoModel model = (OilCardInfoModel) t;
                //绑定油卡成功
                SVProgressHUD.showSuccessWithStatus(aty, "添加成功");

                BaseEvent event = new BaseEvent();
                event.type = IntentKey.Oil.KEY_OIL_MODEL;
                event.model = model;
                EventBus.getDefault().post(event);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            } else if (TextUtils.equals(ConstantTag.BIND_OIL_CARD_FAIL, tag)) {
                //绑卡失败
                dialogRemind();
            }
        }
    }

    /**
     * 绑卡失败，去申请
     */
    private void dialogRemind() {
        DialogUtils.showCommDialog(aty, "您输入的卡号不是加油啦车队卡", "取消", "去办卡", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.DialogDiss();
                showActivity(aty, AskOilCardAty.class);
            }
        });
        DialogUtils.DialogShow();
    }
}
